/*
Copyright (c) 2009 Ben Beaumont

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. 
*/
package com.dogcatfishdish.utils
{
	import com.dogcatfishdish.enum.ColorChannel;
	
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.text.*;

	public class AsciiConverter
	{
		public var channel:uint = ColorChannel.RED;

		public var output:BitmapData;
		public var input:BitmapData;
		
		public var characters:Array;
		public var brightnessValues:Array;
		
		private var charSize:int;
		private var xPos:int = 0;
		private var yPos:int = 0;
		private var imgArray:Array = [];
		private var cellsWidth:uint;
		private var cellsHeight:uint;
		private var totalCells:uint;
		private	var colVal:uint;
		private	var tempBitmapData:BitmapData;
		private	var pt:Point = new Point();
		private var column:uint;
		private var row:int;
		
		/**
		 * Creates a new AsciiConverter instance
		 * @param	input				BitmapData. Instance to be used as the source input.
		 * @param	output				BitmapData. Instance to be used as the ASCII output.
		 * @param	charSize			int. The size of each character, in pixels.
		 * @param	characters			Array. List of characters to be used.
		 * @param	brightnessValues	Array. List of uint between 0 and 0xFF corresponding to the values each character. This array needs to be the same length as the character Array.
		 * @param	font				String. Name of the font to be used. Defaults to '_sans'.
		 * @param	isBold				Boolean. True if the font is bold. Defaults to false.
		 */	 
		public function AsciiConverter(input:BitmapData, 
										output:BitmapData, 
										charSize:int, 
										characters:Array, 
										brightnessValues:Array,
										font:String = '_sans', 
										isBold:Boolean = false)
		{
			this.input = input;
			this.output = output;
			this.charSize = charSize;
			this.characters = characters;
			this.brightnessValues = brightnessValues;

			initDimensions();
			initCharacters(font, isBold);
		}
		
		/**
		 * Generates the ASCII. Can be run once or multiple times for video input.
		 */
		public function update():void
		{
			process();
			reset();
		}
		
		protected function reset():void
		{
			xPos = 0;
			yPos = 0;
		}
		
		protected function initDimensions():void
		{
			cellsWidth = (input.width / (charSize) | 0) + 1;
			cellsHeight = (input.height / charSize | 0) + 1;
			totalCells = cellsHeight * cellsWidth;
		}

		protected function initCharacters(name:String, isBold:Boolean):void
		{
			var charContainer:Sprite = new Sprite();
			
			var charFormat:TextFormat = new TextFormat();
			charFormat.font = font;
			charFormat.bold = isBold;
			charFormat.size = charSize;
			charFormat.align = TextFormatAlign.CENTER;
			
			var charTextField:TextField = new TextField();	
			charTextField.width = charSize;
			charTextField.defaultTextFormat = charFormat;
			charTextField.text = characters[0];
			charTextField.autoSize = TextFieldAutoSize.CENTER;
			charTextField.y -= charTextField.getCharBoundaries(0).y;
			charTextField.width = charSize;
			if(name != '_sans')
				charTextField.embedFonts = true;
			
			charContainer.addChild(charTextField);

			var charBitmapData:BitmapData;
			
			for each(var char:String in characters)
			{
				charTextField.text = char;
					
				charBitmapData = new BitmapData(charSize, charSize, false, 0xFFFFFFFF);
				charBitmapData.draw(charContainer);
			
				imgArray.unshift(charBitmapData);
			}
		}
		
		protected function process():void
		{
			row = -1;
			column = 0;
			
			var i:uint = 0;
			var j:uint;
			var len:uint = brightnessValues.length;
			
			for(; i < totalCells; i++)
			{
				column = i % cellsWidth;
				
				if(column == 0)
					row++;
				
				pt.x = column * charSize;
				pt.y = row * charSize;

				colVal = input.getPixel(pt.x, pt.y) >> channel & 0xFF;

				for(j = 0; j < len; j++)
				{
					if(colVal >= brightnessValues[j])
					{
						tempBitmapData = imgArray[j];
						break;
					}
				}
				
				if (tempBitmapData == null)
					tempBitmapData = imgArray[imgArray.length - 1];
				
				output.copyPixels(tempBitmapData, tempBitmapData.rect, pt);
			}
		}
	}
}